/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.service.impl;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springblade.common.cache.DictCache;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.cache.SysCache;
import org.springblade.common.cache.UserCache;
import org.springblade.common.constant.BaseRoleConstant;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.TenantConstant;
import org.springblade.common.enums.DictEnum;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.*;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.admin.dto.UserTrajectoryDTO;
import org.springblade.modules.admin.dto.feishu.FeiShuUserPerformanceMonthDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.UserTrajectoryEnum;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.UpdateMaintenancePersonnelVO;
import org.springblade.modules.admin.vo.user.UserStatusVo;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.system.entity.*;
import org.springblade.modules.system.enums.UserBusinessSetKeyEnum;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.*;
import org.springblade.modules.system.vo.*;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.common.constant.CommonConstant.DEFAULT_PARAM_PASSWORD;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {
	private static final String GUEST_NAME = "guest";

	private final IUserDeptService userDeptService;
	private final IUserOauthService userOauthService;
	private final IRoleService roleService;
	private final BladeTenantProperties tenantProperties;
	private final IDeptService deptService;
	private final IEstateElevatorUserService estateElevatorUserService;
	private final UserExtService userExtService;
	private final UserCertService userCertService;
	private final UserBusinessSetService userBusinessSetService;
	private final IUserTrajectoryService userTrajectoryService;
	private final BladeRedis bladeRedis;
	private final IUserElevatorBrandService userElevatorBrandService;
	private final IUserElevatorSkillService userElevatorSkillService;
	private final IElevatorBrandService elevatorBrandser;
	private final IDictService dictService;
	private final IMaintainSignCalendarService maintainSignCalendarService;

	private static final String EXCEL_ERR_CACHE = "user:excel:err:";

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(User user) {
		if (StringUtil.isBlank(user.getTenantId())) {
			user.setTenantId(BladeConstant.ADMIN_TENANT_ID);
		}
		String tenantId = user.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}
		if (Func.isNotBlank(user.getRealName())) {
			final String firstLetter = PinyinUtil.getFirstLetter(user.getRealName(), "");
			user.setZhCode(firstLetter.toLowerCase());
		}
		Integer userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
		if (userCount > 0 && Func.isEmpty(user.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		Boolean a = saveUserInfo(user) && submitUserDept(user);

		//2024-07-05 新增用户关联电梯品牌，用户关联电梯技能
		if (user.getUserElevatorBrandIds() != null && user.getUserElevatorBrandIds().size() > 0) {
			List<UserElevatorBrand> userElevatorBrands = new ArrayList<>();
			List<ElevatorBrand> elevatorBrands = elevatorBrandser.listByIds(user.getUserElevatorBrandIds());
			for (ElevatorBrand elevatorBrand : elevatorBrands) {
				UserElevatorBrand userElevatorBrand = new UserElevatorBrand();
				userElevatorBrand.setUserId(user.getId());
				userElevatorBrand.setBrandId(elevatorBrand.getId());
				userElevatorBrand.setBrandName(elevatorBrand.getBrandName());
				userElevatorBrands.add(userElevatorBrand);
			}
			userElevatorBrandService.remove(Wrappers.<UserElevatorBrand>lambdaQuery().eq(UserElevatorBrand::getUserId, user.getId()));
			userElevatorBrandService.saveOrUpdateBatch(userElevatorBrands);
		}
		if (user.getUserElevatorSkillIds() != null && user.getUserElevatorSkillIds().size() > 0) {
			List<UserElevatorSkill> userElevatorSkills = new ArrayList<>();
			List<Dict> dicts = dictService.listByIds(user.getUserElevatorSkillIds());
			for (Dict dict : dicts) {
				UserElevatorSkill userElevatorSkill = new UserElevatorSkill();
				userElevatorSkill.setUserId(user.getId());
				userElevatorSkill.setSkillId(dict.getId());
				userElevatorSkill.setSkillKey(Convert.toInt(dict.getDictKey()));
				userElevatorSkill.setSkillName(dict.getDictValue());
				userElevatorSkills.add(userElevatorSkill);
			}
			userElevatorSkillService.remove(Wrappers.<UserElevatorSkill>lambdaQuery().eq(UserElevatorSkill::getUserId, user.getId()));
			userElevatorSkillService.saveOrUpdateBatch(userElevatorSkills);
		}

		return true;
	}

	@Transactional(rollbackFor = Exception.class)
	public boolean saveUserInfo(User user) {
		boolean save = save(user);
		// 2024-03-28 新增人员轨迹
		if (save) {
			// 封装用户轨迹信息：经纬度、id
			if (Func.isNotEmpty(user.getLatitude()) && Func.isNotEmpty(user.getLongitude())) {
				Long userId = user.getId();
				UserTrajectoryDTO userTrajectoryDTO = new UserTrajectoryDTO();
				userTrajectoryDTO.setUserId(userId);
				userTrajectoryDTO.setOperation(UserTrajectoryEnum.OPERATION_NO_OPERATE.getValue());
				userTrajectoryDTO.setLatitude(user.getLatitude());
				userTrajectoryDTO.setLongitude(user.getLongitude());
				// 记录类型：1-工单定位 2-日常定位 3-打卡定位
				userTrajectoryDTO.setRecordType(2);
				userTrajectoryService.record(userTrajectoryDTO);
			}
		}

		// 更新用户关联证件信息
		userCertService.batchSaveOrUpdate(user.getId(), user.getUserCerts());

		// 关联用户关联表信息
		UserExt userExt = userExtService.getOne(Wrappers.<UserExt>lambdaQuery().eq(UserExt::getUserId, user.getId()));
		if (ObjectUtil.isEmpty(userExt)) {
			userExt = new UserExt();
		}
		userExt.setUserId(user.getId());
		userExt.setAddress(user.getAddress());
		userExt.setLongitude(user.getLongitude());
		userExt.setLatitude(user.getLatitude());
		userExt.setVehicle(user.getVehicle());
		userExt.setSubCom(user.getSubCom());
		userExt.setLocation(user.getLocation());
		userExtService.saveOrUpdate(userExt);

		// 关联用户业务开关表信息
		UserBusinessSet userBusinessSet = userBusinessSetService.getOne(Wrappers.<UserBusinessSet>lambdaQuery().eq(UserBusinessSet::getConfigKey, UserBusinessSetKeyEnum.CHECK_CONTENT_ALL.getType()).eq(UserBusinessSet::getUserId, user.getId()));
		if (ObjectUtil.isEmpty(userBusinessSet)) {
			userBusinessSet = new UserBusinessSet();
			userBusinessSet.setUserId(user.getId());
			userBusinessSet.setConfigKey(UserBusinessSetKeyEnum.CHECK_CONTENT_ALL.getType());
		}
		userBusinessSet.setConfigValue(user.getCheckContentAll());
		userBusinessSetService.saveOrUpdate(userBusinessSet);
		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUser(User user) {
		String tenantId = user.getTenantId();
		Integer userCount = baseMapper.selectCount(
			Wrappers.<User>query().lambda()
				.eq(User::getTenantId, tenantId)
				.eq(User::getAccount, user.getAccount())
				.notIn(User::getId, user.getId())
		);
		if (userCount > 0) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}

		// 删除电梯管理人
		if (Objects.equals(2, user.getStatus())) {
			estateElevatorUserService.removeByUserIds(Arrays.asList(user.getId()));
		}

		if (Func.isNotBlank(user.getRealName())) {
			final String firstLetter = PinyinUtil.getFirstLetter(user.getRealName(), "");
			user.setZhCode(firstLetter.toLowerCase());
		}


		//2024-07-05 新增用户关联电梯品牌，用户关联电梯技能
		if (user.getUserElevatorBrandIds() != null && user.getUserElevatorBrandIds().size() > 0) {
			List<UserElevatorBrand> userElevatorBrands = new ArrayList<>();
			List<ElevatorBrand> elevatorBrands = elevatorBrandser.listByIds(user.getUserElevatorBrandIds());
			for (ElevatorBrand elevatorBrand : elevatorBrands) {
				UserElevatorBrand userElevatorBrand = new UserElevatorBrand();
				userElevatorBrand.setUserId(user.getId());
				userElevatorBrand.setBrandId(elevatorBrand.getId());
				userElevatorBrand.setBrandName(elevatorBrand.getBrandName());
				userElevatorBrands.add(userElevatorBrand);
			}
			userElevatorBrandService.remove(Wrappers.<UserElevatorBrand>lambdaQuery().eq(UserElevatorBrand::getUserId, user.getId()));
			userElevatorBrandService.saveOrUpdateBatch(userElevatorBrands);
		}
		if (user.getUserElevatorSkillIds() != null && user.getUserElevatorSkillIds().size() > 0) {
			List<UserElevatorSkill> userElevatorSkills = new ArrayList<>();
			List<Dict> dicts = dictService.listByIds(user.getUserElevatorSkillIds());
			for (Dict dict : dicts) {
				UserElevatorSkill userElevatorSkill = new UserElevatorSkill();
				userElevatorSkill.setUserId(user.getId());
				userElevatorSkill.setSkillId(dict.getId());
				userElevatorSkill.setSkillKey(Convert.toInt(dict.getDictKey()));
				userElevatorSkill.setSkillName(dict.getDictValue());
				userElevatorSkills.add(userElevatorSkill);
			}
			userElevatorSkillService.remove(Wrappers.<UserElevatorSkill>lambdaQuery().eq(UserElevatorSkill::getUserId, user.getId()));
			userElevatorSkillService.saveOrUpdateBatch(userElevatorSkills);
		}


		return updateUserInfo(user) && submitUserDept(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUserInfo(User user) {
		// 更新用户关联证件信息
		userCertService.batchSaveOrUpdate(user.getId(), user.getUserCerts());

		// 关联用户关联表信息
		UserExt userExt = userExtService.getOne(Wrappers.<UserExt>lambdaQuery().eq(UserExt::getUserId, user.getId()));
		if (ObjectUtil.isEmpty(userExt)) {
			userExt = new UserExt();
		}
		userExt.setUserId(user.getId());
		userExt.setAddress(user.getAddress());
		userExt.setLongitude(user.getLongitude());
		userExt.setLatitude(user.getLatitude());
		userExt.setVehicle(user.getVehicle());
		userExt.setShowInfo(user.getShowInfo());
		userExt.setSubCom(user.getSubCom());
		userExt.setLocation(user.getLocation());
		userExtService.saveOrUpdate(userExt);

		// 关联用户业务开关表信息
		UserBusinessSet userBusinessSet = userBusinessSetService.getOne(Wrappers.<UserBusinessSet>lambdaQuery().eq(UserBusinessSet::getConfigKey, UserBusinessSetKeyEnum.CHECK_CONTENT_ALL.getType()).eq(UserBusinessSet::getUserId, user.getId()));
		if (ObjectUtil.isEmpty(userBusinessSet)) {
			userBusinessSet = new UserBusinessSet();
			userBusinessSet.setUserId(user.getId());
			userBusinessSet.setConfigKey(UserBusinessSetKeyEnum.CHECK_CONTENT_ALL.getType());
		}
		userBusinessSet.setConfigValue(user.getCheckContentAll());
		userBusinessSetService.saveOrUpdate(userBusinessSet);

		user.setPassword(null);
		return updateById(user);
	}

	private boolean submitUserDept(User user) {
		List<Long> deptIdList = Func.toLongList(user.getDeptId());
		List<UserDept> userDeptList = new ArrayList<>();
		deptIdList.forEach(deptId -> {
			UserDept userDept = new UserDept();
			userDept.setUserId(user.getId());
			userDept.setDeptId(deptId);
			userDeptList.add(userDept);
		});
		userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
		return userDeptService.saveBatch(userDeptList);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user, Long deptId, String tenantId) {
		List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
		return page.setRecords(baseMapper.selectUserPage(page, user, deptIdList, tenantId));
	}

	@Override
	public IPage<UserVO> selectUserSearch(UserVO user, Query query) {
		LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
		if (StringUtil.isNotBlank(user.getName())) {
			queryWrapper.like(User::getName, user.getName());
		}
		if (StringUtil.isNotBlank(user.getDeptName())) {
			String deptIds = SysCache.getDeptIdsByFuzzy(AuthUtil.getTenantId(), user.getDeptName());
			if (StringUtil.isNotBlank(deptIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(deptIds);
					ids.forEach(id -> wrapper.like(User::getDeptId, id).or());
				});
			}
		}
		if (StringUtil.isNotBlank(user.getPostName())) {
			String postIds = SysCache.getPostIdsByFuzzy(AuthUtil.getTenantId(), user.getPostName());
			if (StringUtil.isNotBlank(postIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(postIds);
					ids.forEach(id -> wrapper.like(User::getPostId, id).or());
				});
			}
		}
		IPage<User> pages = this.page(Condition.getPage(query), queryWrapper);
		return UserWrapper.build().pageVO(pages);
	}

	@Override
	public User userByAccount(String tenantId, String account) {
		return baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		User user = baseMapper.selectById(userId);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password) {
		User user = baseMapper.getUser(tenantId, account, password);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password, UserEnum userEnum) {
		User user = baseMapper.getUser(tenantId, account, password);
		return buildUserInfo(user, userEnum);
	}

	@Override
	public UserInfo userInfo(String tenantId, String phone, UserEnum userEnum) {
		User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getTenantId, tenantId).eq(User::getPhone, phone).eq(User::getIsDeleted, 0));
		if (user == null) {
			throw new ServiceException("未找到相关账号!");
		}
		return buildUserInfo(user, userEnum);
	}

	private UserInfo buildUserInfo(User user) {
		return buildUserInfo(user, UserEnum.WEB);
	}

	private UserInfo buildUserInfo(User user, UserEnum userEnum) {
		if (ObjectUtil.isEmpty(user)) {
			return null;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		userInfo.setStatus(user.getStatus());
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
			userInfo.setRoles(roleAlias);
		}
		// 根据每个用户平台，建立对应的detail表，通过查询将结果集写入到detail字段
		Kv detail = Kv.create().set("type", userEnum.getName());
		detail.set("phone", user.getPhone());
		if (userEnum == UserEnum.WEB) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else if (userEnum == UserEnum.APP) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		}
		userInfo.setDetail(detail);
		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserInfo userInfo(UserOauth userOauth) {
		UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
		UserInfo userInfo;
		if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
			userInfo = this.userInfo(uo.getUserId());
			userInfo.setOauthId(Func.toStr(uo.getId()));
		} else {
			userInfo = new UserInfo();
			if (Func.isEmpty(uo)) {
				userOauthService.save(userOauth);
				userInfo.setOauthId(Func.toStr(userOauth.getId()));
			} else {
				userInfo.setOauthId(Func.toStr(uo.getId()));
			}
			User user = new User();
			user.setAccount(userOauth.getUsername());
			user.setTenantId(userOauth.getTenantId());
			userInfo.setUser(user);
			userInfo.setRoles(Collections.singletonList(GUEST_NAME));
		}
		return userInfo;
	}

	@Override
	public boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
		user.setUpdateTime(DateUtil.now());
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
		User user = getById(userId);
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeUser(String userIds) {
		if (Func.contains(Func.toLongArray(userIds), AuthUtil.getUserId())) {
			throw new ServiceException("不能删除本账号!");
		}

		// 删除电梯管理人
		estateElevatorUserService.removeByUserIds(Func.toLongList(userIds));

		return deleteLogic(Func.toLongList(userIds)) && userDeptService.remove(Wrappers.<UserDept>lambdaQuery().in(UserDept::getUserId, Func.toLongList(userIds)));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importUser(List<UserExcel> data, Boolean isCovered) {
		data.forEach(userExcel -> {
			User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
			// 设置用户平台
			user.setUserType(Func.toInt(DictCache.getKey(DictEnum.USER_TYPE, userExcel.getUserTypeName()), 1));
			// 设置部门ID
			user.setDeptId(Func.toStrWithEmpty(SysCache.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()), StringPool.EMPTY));
			// 设置岗位ID
			user.setPostId(Func.toStrWithEmpty(SysCache.getPostIds(userExcel.getTenantId(), userExcel.getPostName()), StringPool.EMPTY));
			// 设置角色ID
			user.setRoleId(Func.toStrWithEmpty(SysCache.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()), StringPool.EMPTY));
			// 设置租户ID
			if (!AuthUtil.isAdministrator() || StringUtil.isBlank(user.getTenantId())) {
				user.setTenantId(AuthUtil.getTenantId());
			}
			// 覆盖数据
			if (isCovered) {
				// 查询用户是否存在
				User oldUser = UserCache.getUser(userExcel.getTenantId(), userExcel.getAccount());
				if (oldUser != null && oldUser.getId() != null) {
					user.setId(oldUser.getId());
					this.updateUser(user);
					return;
				}
			}
			// 获取默认密码配置
			String initPassword = ParamCache.getValue(DEFAULT_PARAM_PASSWORD);
			user.setPassword(initPassword);
			this.submit(user);
		});
	}

	@Override
	public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
		List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
		userList.forEach(user -> {
			user.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
			user.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
			user.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
			user.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
		});
		return userList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerGuest(User user, Long oauthId) {
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		UserOauth userOauth = userOauthService.getById(oauthId);
		if (userOauth == null || userOauth.getId() == null) {
			throw new ServiceException("第三方登陆信息错误!");
		}
		user.setRealName(user.getName());
		user.setAvatar(userOauth.getAvatar());
		user.setRoleId(StringPool.MINUS_ONE);
		user.setDeptId(StringPool.MINUS_ONE);
		user.setPostId(StringPool.MINUS_ONE);
		boolean userTemp = this.submit(user);
		userOauth.setUserId(user.getId());
		userOauth.setTenantId(user.getTenantId());
		boolean oauthTemp = userOauthService.updateById(userOauth);
		return (userTemp && oauthTemp);
	}

	@Override
	public boolean updatePlatform(Long userId, Integer userType, String userExt) {
		if (userType.equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userWeb.setId(query.getId());
			}
			userWeb.setUserId(userId);
			userWeb.setUserExt(userExt);
			return userWeb.insertOrUpdate();
		} else if (userType.equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userApp.setId(query.getId());
			}
			userApp.setUserId(userId);
			userApp.setUserExt(userExt);
			return userApp.insertOrUpdate();
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userOther.setId(query.getId());
			}
			userOther.setUserId(userId);
			userOther.setUserExt(userExt);
			return userOther.insertOrUpdate();
		}
	}

	@Override
	public UserVO platformDetail(User user) {
		User detail = baseMapper.selectOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		if (userVO.getUserType().equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else if (userVO.getUserType().equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		}
		return userVO;
	}

	@Override
	public SimpleUserVO getSimpleUserInfo(Long userId) {
		return baseMapper.getSimpleUserInfo(userId);
	}

	@Override
	public List<SimpleUserVO> getEstateSimpleUserInfo(List<Long> userIds) {
		return baseMapper.getEstateSimpleUserInfo(userIds);
	}

	@Override
	public SimpleUserVO getSimpleUserInfoByPhone(String phone) {
		return baseMapper.getSimpleUserInfoByPhone(phone);
	}

	@Override
	public SimpleUserVO getEstateSimpleUserInfoByPhone(String phone) {
		return baseMapper.getEstateSimpleUserInfoByPhone(phone);
	}

	@Override
	public List<SimpleUserVO> getUserByDeptAndRole(Long deptId, Long roleId) {
		return baseMapper.getUserByDeptAndRole(deptId, roleId);
	}

	@Override
	public ApproveUserVO getApproveUser(Long submitId) {
		Set<SimpleUserVO> groupLeaders = new LinkedHashSet<>();
		Set<SimpleUserVO> managerNames = new LinkedHashSet<>();

		String tenantId = AuthUtil.getTenantId();
		// 组长角色
		Long groupRoleId = roleService.getRoleIdByAliases(tenantId, BaseRoleConstant.MAINTENANCE_GROUP_LEADER);
		// 经理角色
		Long managerRoleId = roleService.getRoleIdByAliases(tenantId, BaseRoleConstant.MAINTENANCE_MANAGER);

		// 标记已查找的部门
		List<Long> deptFlag = new ArrayList<>();
		// 提交人所在部门祖级列表
		List<String> deptAncestors = deptService.getAncestorsByUserId(submitId);
		for (String deptAncestor : deptAncestors) {
			List<Long> deptIds = Func.toLongList(deptAncestor);
			// 提交者所在部门
			Long curDeptId = deptIds.get(deptIds.size() - 1);
			// 所在组“组长”角色用户集合
			List<SimpleUserVO> groupUsers = this.getUserByDeptAndRole(curDeptId, groupRoleId);
			if (Func.isNotEmpty(groupUsers)) {
				groupLeaders.addAll(groupUsers);
			}

			// 从所在部门依次往上寻找“经理”角色用户集合
			for (int i = deptIds.size() - 1; i > 0; i--) {
				if (deptFlag.contains(deptIds.get(i))) {
					continue;
				}
				deptFlag.add(deptIds.get(i));
				List<SimpleUserVO> managerUsers = this.getUserByDeptAndRole(deptIds.get(i), managerRoleId);
				if (Func.isNotEmpty(managerUsers)) {
					managerNames.addAll(managerUsers);
					break;
				}
			}
		}

		/**
		 * 若找不到维保经理，则取管理员
		 * 若找不到维保组长，则取维保经理
		 */
		if (Func.isEmpty(managerNames)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			List<SimpleUserVO> adminUsers = this.getUserByDeptAndRole(null, adminRoleId);
			managerNames.addAll(adminUsers);
		}
		if (Func.isEmpty(groupLeaders)) {
			groupLeaders.addAll(managerNames);
		}

		// 数据封装
		ApproveUserVO approveUserVO = new ApproveUserVO();
		approveUserVO.setGroupUsers(groupLeaders);
		approveUserVO.setManagerUsers(managerNames);

		return approveUserVO;
	}

	@Override
	public ApproveUserDataVO getApproveUserData(Long submitId) {
		ApproveUserVO approveUser = this.getApproveUser(submitId);
		String groupApproveIds = approveUser.getGroupUsers().stream().map(t -> String.valueOf(t.getUserId())).collect(Collectors.joining(","));
		String groupApproveNames = approveUser.getGroupUsers().stream().map(t -> t.getUserName()).collect(Collectors.joining(","));

		Set<SimpleUserVO> mergeUsers = new LinkedHashSet<>();
		mergeUsers.addAll(approveUser.getGroupUsers());
		mergeUsers.addAll(approveUser.getManagerUsers());
		String approveIds = mergeUsers.stream().map(t -> String.valueOf(t.getUserId())).collect(Collectors.joining(","));
		String approveNames = mergeUsers.stream().map(t -> t.getUserName()).collect(Collectors.joining(","));

		ApproveUserDataVO approveUserDataVO = new ApproveUserDataVO();
		approveUserDataVO.setGroupApproveIds(groupApproveIds);
		approveUserDataVO.setGroupApproveNames(groupApproveNames);
		approveUserDataVO.setApproveIds(approveIds);
		approveUserDataVO.setApproveNames(approveNames);
		return approveUserDataVO;
	}

	@Override
	public List<User> selectUserByRole(List<Long> roleIds, String tenantId) {
		return baseMapper.selectUserByRole(roleIds, tenantId);
	}

	@Override
	public List<Long> getUserByRoleName(String roleName) {
		String tenantId = AuthUtil.getTenantId();
		return this.getUserByRoleName(tenantId, roleName);
	}

	@Override
	public List<Long> getUserByRoleName(String tenantId, String roleName) {
		Long roleId = roleService.getRoleIdByAliases(tenantId, roleName);
		List<Long> userIds = baseMapper.getUserByRoleId(tenantId, roleId);

		// 若找不到对应用户，admin角色兜底
		if (Func.isEmpty(userIds)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			userIds = baseMapper.getUserIdByDeptAndRole(null, adminRoleId);
		}

		return userIds;
	}

	@Override
	public List<Long> getUserByOwnDeptParent(Long applyUserId, String roleNames) {
		List<Long> userIds = new ArrayList<>();
		String tenantId = AuthUtil.getTenantId();
		List<String> roleNameList = Func.toStrList(roleNames);
		// 标记 最后一个角色才开始逐级往上找
		int sizeFlag = roleNameList.size();
		for (String roleName : roleNameList) {
			Long roleId = roleService.getRoleIdByAliases(tenantId, roleName);
			// 提交人所在部门祖级列表
			List<String> deptAncestors = deptService.getAncestorsByUserId(applyUserId);
			for (String deptAncestor : deptAncestors) {
				List<Long> deptIds = Func.toLongList(deptAncestor);
				// 提交者所在部门
				Long curDeptId = deptIds.get(deptIds.size() - 1);
				// 所在组角色用户集合
				List<Long> firstUsers = baseMapper.getUserIdByDeptAndRole(curDeptId, roleId);
				if (Func.isNotEmpty(firstUsers)) {
					userIds.addAll(firstUsers);
					break;
				} else {
					if (--sizeFlag == 0) {
						// 从所在部门依次往上寻找角色用户集合
						for (int i = deptIds.size() - 1; i > 0; i--) {
							List<Long> otherUsers = baseMapper.getUserIdByDeptAndRole(deptIds.get(i), roleId);
							if (Func.isNotEmpty(otherUsers)) {
								userIds.addAll(otherUsers);
								break;
							}
						}
					}
				}
			}

			if (Func.isNotEmpty(userIds)) {
				break;
			}
		}

		/**
		 * 若找不到对应用户，admin角色兜底
		 */
		if (Func.isEmpty(userIds)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			List<Long> adminUsers = baseMapper.getUserIdByDeptAndRole(null, adminRoleId);
			userIds.addAll(adminUsers);
		}

		return userIds;
	}

	@Override
	public List<String> getDeptNames(Long userId) {

		return baseMapper.getDeptNames(userId);
	}

	@Override
	public List<User> list(User user, BladeUser bladeUser, Boolean isSign) {
		if (user.getStatus() == null) {
			user.setStatus(-1);
		}
		Long signSetingId = null;
		if (isSign) {
			MaintainSignCalendar maintainSignCalendar = maintainSignCalendarService.getOne(Wrappers.<MaintainSignCalendar>lambdaQuery().orderByDesc(MaintainSignCalendar::getCreateTime).last("limit 1"));
			signSetingId = maintainSignCalendar.getSignSetingId();
		}

		return baseMapper.getTenantUserList(user, bladeUser, signSetingId);
	}

	@Override
	public List<UserStatusVo> getUserStatusList() {
		final String tenantId = AuthUtil.getTenantId();
		return baseMapper.getUserStatusList(tenantId);
	}

	@Override
	public List<User> listAllMaintainUser() {
		return baseMapper.listAllMaintainUser();
	}

	/**
	 * 忽略租户，查询全部用户
	 *
	 * @return 用户集合
	 */
	@Override
	@TenantIgnore
	public List<UpdateMaintenancePersonnelVO> queryUpdateMaintenancePersonnelVOList() {
		return baseMapper.queryUpdateMaintenancePersonnelVOList();
	}

	@Override
	public Boolean updateDeptBatch(List<User> userList) {
		userList.forEach(e -> {
			if (Func.isNotBlank(e.getDeptId())) {
				submitUserDept(e);
			}
		});
		return super.updateBatchById(userList);
	}

	@Override
	public void downElevatorTemplate(HttpServletResponse response, Integer level) {
		XSSFWorkbook workbook = this.initExcelTemplate(level);

		String fileName = cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			CommonUtil.setResponseHeader(response, fileName);
			workbook.write(outputStream);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (workbook != null) {
					workbook.close();
				}
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> uploadExcel(List<Map<String, Object>> readAll, Integer level, Integer temp) {

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("total", readAll.size());

		List<User> userList = new ArrayList<>();
		LinkedList<Map<String, Object>> errorList = new LinkedList<>();
		// 交通工具数据源
		Map<String, String> vehicleMap = DictCache.getList("vehicle").stream().collect(Collectors.toMap(Dict::getDictValue, Dict::getDictKey));
		// 已有用户数据
		List<User> users = super.list(Wrappers.<User>lambdaQuery().eq(User::getLevel, level));
		Map<String, Long> usersGroup = new HashMap<>();
//		Map<Long,Long> userExtsGroup = new HashMap<>();
		List<String> phoneList = new ArrayList<>();
		if (Func.isNotEmpty(users)) {
			phoneList = users.stream().map(User::getPhone).collect(Collectors.toList());
			usersGroup = users.stream().collect(Collectors.toMap(User::getPhone, User::getId));
		}
		// 角色数据源
		Long roleId = roleService.getRoleIdByAliases(AuthUtil.getTenantId(), "external_personnel");

		// 部门数据源
		List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery().eq(Dept::getTenantId, AuthUtil.getTenantId()));
		List<String> deptNamesPath = new ArrayList<>();
		List<List<Long>> deptIdsPath = new ArrayList<>();
		if (Func.isNotEmpty(deptList)) {
			Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Dept::getDeptName));
			deptList.forEach(e -> {
				List<Long> deptIds = Func.toLongList(e.getAncestors() + "," + e.getId());
				deptIdsPath.add(deptIds);
				List<String> deptNames = new ArrayList<>();
				deptIds.forEach(t -> {
					if (Func.isNotBlank(deptMap.get(t))) {
						deptNames.add(deptMap.get(t));
					}
				});
				deptNamesPath.add(String.join("/", deptNames));
			});
		}

		for (Map<String, Object> stringObjectMap : readAll) {

			User user = new User();

			// 所属公司
			String subCom = Convert.toStr(stringObjectMap.get("所属公司"));
			user.setSubCom(subCom);

			// 关联机构（必填）
			String dept = Convert.toStr(stringObjectMap.get("关联机构（必填）"));
			if (Func.isBlank(dept)) {
				stringObjectMap.put("备注", "关联机构不可为空");
				errorList.add(stringObjectMap);
				continue;
			}
			if (Func.isNotEmpty(deptNamesPath)) {
				List<Integer> index = new ArrayList<>();
				List<String> deptId = new ArrayList<>();
				for (int i = 0; i < deptNamesPath.size(); i++) {
					if (deptNamesPath.get(i).equals(dept)) {
						index.add(i);
					}
				}
				if (Func.isNotEmpty(index)) {
					index.forEach(e -> {
						List<Long> c = deptIdsPath.get(e);
						deptId.add(String.valueOf(c.get(c.size() - 1)));
					});
					user.setDeptId(String.join(",", deptId));
				} else {
					stringObjectMap.put("备注", "部门不存在");
					errorList.add(stringObjectMap);
					continue;
				}
			}

			// 姓名（必填）
			String realName = Convert.toStr(stringObjectMap.get("姓名（必填）"));
			if (Func.isBlank(realName)) {
				stringObjectMap.put("备注", "姓名不可为空");
				errorList.add(stringObjectMap);
				continue;
			}
			user.setRealName(realName);

			// 手机号（必填）
			String phone = Convert.toStr(stringObjectMap.get("手机号（必填）"));
			long phoneCount = 0;
			if (Func.isNotEmpty(userList)) {
				phoneCount = userList.stream().filter(e -> e.getPhone().equals(phone)).count();
			}
			if (Func.isBlank(phone) || phone.length() != 11 || phoneList.contains(phone) || phoneCount > 0) {
				stringObjectMap.put("备注", "手机号验证失败或已存在");
				errorList.add(stringObjectMap);
				continue;
			}
			user.setPhone(phone);

			// 性别
			String sex = Convert.toStr(stringObjectMap.get("性别"));
			user.setSex(Func.isBlank(sex) ? 3 : "男".equals(sex) ? 1 : 2);

			// 生日
			String birthday = Convert.toStr(stringObjectMap.get("生日"));
			if (Func.isNotBlank(birthday)) {
				Date date = null;
				try {
					date = DateUtil.parse(birthday, "yyyy/M/d");
				} catch (Exception e) {
				}
				user.setBirthday(date);
			}

			// 昵称
			String name = Convert.toStr(stringObjectMap.get("昵称"));
			user.setName(name);

			// 交通工具（必填）
			String vehicle = Convert.toStr(stringObjectMap.get("交通工具（必填）"));
			if (Func.isBlank(vehicle) || !vehicleMap.containsKey(vehicle)) {
				stringObjectMap.put("备注", "交通工具不可为空");
				errorList.add(stringObjectMap);
				continue;
			}
			user.setVehicle(vehicleMap.get(vehicle));

			// 详细住址（必填）
			String location = Convert.toStr(stringObjectMap.get("详细住址（必填）"));
			if (Func.isBlank(location)) {
				stringObjectMap.put("备注", "详细住址不可为空");
				errorList.add(stringObjectMap);
				continue;
			}
			user.setLocation(location);

			// 所属角色
			user.setRoleId(String.valueOf(roleId));
			// 人员等级
			user.setLevel(level);
			user.setAccount(phone);
			user.setPassword(DigestUtil.md5Hex(phone));
			final String firstLetter = PinyinUtil.getFirstLetter(user.getRealName(), "");
			user.setZhCode(firstLetter.toLowerCase());
			user.setTenantId(AuthUtil.getTenantId());
//			if(temp.equals(2) && usersGroup.containsKey(user.getPhone())){
//				user.setId(usersGroup.get(user.getPhone()));
//			}
			userList.add(user);
		}

		if (Func.isNotEmpty(userList)) {

			List<List<User>> resultList = ListUtil.partition(userList, 50);
			resultList.forEach(k -> {
				super.saveOrUpdateBatch(k);

				List<UserExt> userExts = new ArrayList<>();
				k.forEach(e -> {
					UserExt userExt = new UserExt();
					userExt.setUserId(e.getId());
					userExt.setVehicle(e.getVehicle());
					userExt.setLocation(e.getLocation());
					userExt.setSubCom(e.getSubCom());
					userExt.setTenantId(AuthUtil.getTenantId());
					userExts.add(userExt);
				});

				List<UserDept> userDeptList = new ArrayList<>();
				k.forEach(e -> {
					if (Func.isNotBlank(e.getDeptId())) {
						List<Long> deptIds = Func.toLongList(e.getDeptId());
						deptIds.forEach(t -> {
							UserDept userDept = new UserDept();
							userDept.setUserId(e.getId());
							userDept.setDeptId(t);
							userDeptList.add(userDept);
						});
					}
				});

//				userDeptService.remove(Wrappers.<UserDept>lambdaQuery().in(UserDept::getUserId,userDeptList.stream().map(UserDept::getUserId).collect(Collectors.toList())));
				userDeptService.saveBatch(userDeptList);
				userExtService.saveBatch(userExts);
			});
		}

		// 将出错数据存到redis
		if (errorList.size() > 0) {
			bladeRedis.setEx(AuthUtil.getTenantId().concat(StringPool.COLON).concat(EXCEL_ERR_CACHE).concat(String.valueOf(level)), errorList, 30000L);
		}

		resultMap.put("success", userList.size());
		resultMap.put("error", errorList.size());
		return resultMap;
	}

	private void findTreePathNames(List<List<String>> namesResult, DeptVO e, List<String> namesPath, List<List<Long>> idsResult, List<Long> idsPath) {
		if (Func.isEmpty(e.getChildren())) {
			namesResult.add(namesPath);
			idsResult.add(idsPath);
			return;
		}
		for (int i = 0; i < e.getChildren().size(); i++) {
			DeptVO child = e.getChildren().get(i);
			List<String> cNamesPath = new ArrayList<>();
			cNamesPath.addAll(namesPath);
			cNamesPath.add(child.getTitle());
			List<Long> cIdsPath = new ArrayList<>();
			cIdsPath.addAll(idsPath);
			cIdsPath.add(child.getId());
			this.findTreePathNames(namesResult, child, cNamesPath, idsResult, cIdsPath);
		}
	}

	@Override
	public void downErrExcel(HttpServletResponse response, Integer level) {
		Object data = bladeRedis.get(AuthUtil.getTenantId().concat(StringPool.COLON).concat(EXCEL_ERR_CACHE).concat(String.valueOf(level)));
		if (Func.isEmpty(data)) {
			throw new ServiceException("未有错误数据导出！");
		}
		LinkedList<Map<String, Object>> errList = (LinkedList<Map<String, Object>>) data;

		Map<Integer, String> titleMap = this.intiExcelTitle(level);
		XSSFWorkbook workbook = this.initExcelTemplate(level);
		XSSFSheet sheet = workbook.getSheetAt(0);
		for (int i = 0; i < errList.size(); i++) {
			Map<String, Object> itemMap = errList.get(i);
			XSSFRow row = sheet.createRow(i + 2);
			row.setHeightInPoints(20);
			titleMap.forEach((tKey, tValue) -> {
				XSSFCell cell = row.createCell(tKey);
				cell.setCellValue(Convert.toStr(itemMap.get(tValue)));
			});
		}
		String fileName = "error-" + cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			CommonUtil.setResponseHeader(response, fileName);
			workbook.write(outputStream);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (workbook != null) {
					workbook.close();
				}
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void downExcelDetail(User user, List<List<String>> rows) {
		List<User> users = baseMapper.listUser(user);
		users.forEach(e -> {
			List<String> row = new ArrayList<>(11);
			row.add(Convert.toStr(e.getSubCom()));
			row.add(Convert.toStr(e.getDeptNames()));
			row.add(Convert.toStr(e.getRealName()));
			row.add(Convert.toStr(e.getPhone()));
			String sexName = Func.isEmpty(e.getSex()) || e.getSex() == 3 ? "未知" : e.getSex() == 1 ? "男" : "女";
			row.add(Convert.toStr(sexName));
			row.add(Convert.toStr(Func.isNotEmpty(e.getBirthday()) ? DateUtil.format(e.getBirthday(), "yyyy/M/d") : ""));
			row.add(Convert.toStr(e.getName()));
			row.add(Convert.toStr(e.getVehicleName()));
			row.add(Convert.toStr(e.getLocation()));
			rows.add(row);
		});
	}

	@Override
	public List<User> getUserListOfRoleCode(String roleCode, String tenantId) {
		return baseMapper.getUserListOfRoleCode(roleCode, tenantId);
	}

	@Override
	public String getUserAppPushId(Long userId) {
		return baseMapper.getUserAppPushId(userId);
	}

	@Override
	public List<FeiShuUserPerformanceMonthDTO> selectSimpleUserPerformanceMonthByIds(List<Long> userIds) {
		return baseMapper.selectSimpleUserPerformanceMonthByIds(userIds);
	}

	@Override
	public List<SimpleUserVO> getSimpleUserInfoList(List<Long> userIds) {
		return baseMapper.getSimpleUserInfoList(userIds);
	}

	private Map<Integer, String> intiExcelTitle(Integer level) {
		Map<Integer, String> titleMap = new LinkedHashMap<>(16);
		// 固定标题
		String[] fixedTitle = {"所属公司", "关联机构（必填）", "姓名（必填）", "手机号（必填）", "性别", "生日", "昵称", "交通工具（必填）", "详细住址（必填）", "备注"};
		// 动态标题
		for (int i = 0; i < fixedTitle.length; i++) {
			titleMap.put(i, fixedTitle[i]);
		}
		return titleMap;
	}

	private XSSFWorkbook initExcelTemplate(Integer level) {
		XSSFWorkbook workbook = null;
		//读取源文件
		ClassPathResource resource;
		try {
			resource = new ClassPathResource("templates/人员模板.xlsx");
			workbook = new XSSFWorkbook(resource.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			throw new ServiceException("电梯模板文件异常！");
		}

		//进行模板的克隆（接下来的操作都是针对克隆后的sheet）
		XSSFSheet sheet = workbook.cloneSheet(0);
		// 行数
		final int maxRow = 1000;
		// 清空内容
		this.removeRow(sheet, 3, maxRow);

		List<Dict> vehicleList = DictCache.getList("vehicle");
		String[] vehicles = vehicleList.stream().map(Dict::getDictValue).toArray(String[]::new);

		//设置一级下拉
		XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
		XSSFSheet hidden = workbook.createSheet("hidden");
		XSSFCell cell = null;
		for (int i = 0, length = vehicles.length; i < length; i++) {
			String name = vehicles[i];
			XSSFRow row = hidden.createRow(i);
			cell = row.createCell(0);
			cell.setCellValue(name);
		}

		String strFormula = "hidden!$A$1:$A$" + vehicles.length;
		XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST, strFormula);

		// 四个参数分别是：起始行、终止行、起始列、终止列.
		// 1 (一级下拉框代表从excel第1+1行开始) 10(一级下拉框代表从excel第1+10行结束) 1(代表第几列开始，0是第一列，1是第二列) 1(代表第几列结束，0是第一列，1是第二列)
		CellRangeAddressList provinceRangeAddressList = new CellRangeAddressList(2, maxRow, 7, 7);
		DataValidation provinceDataValidation = dvHelper.createValidation(constraint, provinceRangeAddressList);
		provinceDataValidation.createErrorBox("error", "请选择正确数据");
		provinceDataValidation.setShowErrorBox(true);
		//设置sheet是否隐藏  true:隐藏/false:显示
		workbook.setSheetHidden(workbook.getSheetIndex(hidden), true);
		sheet.addValidationData(provinceDataValidation);

		//移除workbook中的模板sheet
		workbook.removeSheetAt(0);
		//给sheet命名
		workbook.setSheetName(0, "人员模板");
		return workbook;
	}

	/**
	 * 从某行开始，清除固定行（清除样式）
	 *
	 * @param sheet
	 * @param startRow
	 * @param endRow
	 */
	private void removeRow(XSSFSheet sheet, int startRow, int endRow) {
		for (int j = endRow; j >= startRow; j--) {
			if (sheet.getRow(j) == null) {
				continue;
			}
			sheet.removeRow(sheet.getRow(j));
		}
	}

	@Override
	public List<SimpleUserVO> getUserByDeptIdsAndRoleAlias(String deptIds, String roleAlias) {
		if (Func.isEmpty(deptIds)) {
			return new ArrayList<>();
		}
		return baseMapper.getUserByDeptIdsAndRoleAlias(deptIds.replace(",", "|"), roleAlias);
	}
}
